package hibari.server.servlet;

import hibari.PMF;
import hibari.client.Configuration;
import hibari.client.model.DownloadToken;

import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class Download extends HttpServlet {
	private static final long serialVersionUID = 2688771898178531547L;
	private Logger logger = Logger.getLogger("DownloadServlet");
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			String uuid = req.getParameter("uuid");
			logger.info("download token requestd: "+ uuid);
			DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
			Query query = new Query("DownloadToken");
			query.addFilter("uuid", FilterOperator.EQUAL, uuid);
			Entity entity = ds.prepare(query).asSingleEntity();
			PersistenceManager pm = PMF.get().getPersistenceManager();
			DownloadToken token = pm.getObjectById(DownloadToken.class, entity.getKey());
			Integer downloadCount = token.getDownloadCount();
			if(downloadCount > Configuration.MAX_DOWNLOAD){
				throw new RuntimeException("Download limitation exceed!");
			}
			
			token.setDownloadCount(downloadCount + 1);
			pm.makePersistent(token);
			pm.close();
			logger.info("count:" + token.getDownloadCount());
			
			resp.getWriter().print(new JsonTemplate().generate(token));
		} catch (Exception e) {
			resp.getWriter().print("{\"state\":\"error\", \"reason\":\"" + e.getMessage() + "\"}");
			e.printStackTrace();
		}
	}
}
